package com.xoa.dev.weLink.service;

import com.xoa.dao.common.SysParaMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.users.UserPrivMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dao.weLink.UserWeLinkMapper;
import com.xoa.dev.qywx.model.QywxUser;
import com.xoa.model.common.SysPara;
import com.xoa.model.department.Department;
import com.xoa.model.modulePriv.ModulePriv;
import com.xoa.model.qiyeWeixin.UserWeixinqy;
import com.xoa.model.users.UserExt;
import com.xoa.model.users.UserPriv;
import com.xoa.model.users.Users;
import com.xoa.model.weLink.UserWeLink;
import com.xoa.service.department.DepartmentService;
import com.xoa.service.users.UsersService;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.http.HttpClientUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WeLinkService {

    @Autowired
    private SysParaMapper sysParaMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private UserPrivMapper userPrivMapper;

    @Autowired
    private UserWeLinkMapper userWeLinkMapper;

    @Autowired
    private UsersService usersService;

    @Autowired
    private DepartmentService departmentService;

    // 企业凭证
    private String ACCESS_TOKEN = "";

    // accessToken 生成时间（两个小时有效期
    private Long accessToken_TimeLimit = new Date().getTime();

    private Map<String,String> headsMap = new HashMap<>();

    // 获取accessToken
    public String getAccessToken(){
        Long CurTimeLimit = new Date().getTime();
        if(StringUtils.checkNull(ACCESS_TOKEN) || (CurTimeLimit-accessToken_TimeLimit)/1000 >7000){

            SysPara welinkAppid = sysParaMapper.querySysPara("WELINK_APPID");
            SysPara welinkAppsecret = sysParaMapper.querySysPara("WELINK_APPSECRET");

            Map<String,String> map = new HashMap<>();
            map.put("client_id",welinkAppid.getParaValue());
            map.put("client_secret",welinkAppsecret.getParaValue());
            JSONObject res = JSONObject.fromObject(HttpClientUtil.doPost("https://open.welink.huaweicloud.com/api/auth/v2/tickets", map, "utf-8"));
            if(res.get("code").equals("0") ){
                ACCESS_TOKEN = (String) res.get("access_token");
            }
        }
        return ACCESS_TOKEN;
    }

    public String getWlUserIdByCode(String code){
        JSONObject res = null;
        if(!StringUtils.checkNull(code)){
            headsMap.put("x-wlk-Authorization",getAccessToken());
            res = HttpClientUtil.httpGetWithHeads("https://open.welink.huaweicloud.com/api/auth/v2/userid?&code="+code,headsMap);
            if(res.get("code").equals("0")){
                return res.getString("userId");
            }
        }
        return null;
    }

    /**
     * @接口说明:  获取单个部门信息
     * @日期: 2020/3/10
     * @作者: 张航宁
     */
    public JSONObject getDepartment(String deptCode){
        JSONObject res = null;
        if(!StringUtils.checkNull(deptCode)){
            headsMap.put("x-wlk-Authorization",getAccessToken());
            res = HttpClientUtil.httpGetWithHeads("https://open.welink.huaweicloud.com/api/contact/v1/departments/"+deptCode,headsMap);
        } else {
            deptCode= "0";
            headsMap.put("x-wlk-Authorization",getAccessToken());
            res = HttpClientUtil.httpGetWithHeads("https://open.welink.huaweicloud.com/api/contact/v1/departments/"+deptCode,headsMap);
        }
        return res;
    }

    /**
     * @接口说明:  获取子部门信息
     * @日期: 2020/3/10
     * @作者: 张航宁
     */
    public JSONArray getDepartments(String deptCode){
        JSONArray res = null;
        if(!StringUtils.checkNull(deptCode)){
            headsMap.put("x-wlk-Authorization",getAccessToken());
            JSONObject object = HttpClientUtil.httpGetWithHeads("https://open.welink.huaweicloud.com/api/contact/v2/departments/list?offset=1&limit=100&recursiveflag=0&deptCode="+deptCode,headsMap);
            if(object!=null&&"0".equals(object.getString("code"))){
                res = object.getJSONArray("departmentInfo");
            }
        } else {
            deptCode = "0";
            headsMap.put("x-wlk-Authorization",getAccessToken());
            JSONObject object = HttpClientUtil.httpGetWithHeads("https://open.welink.huaweicloud.com/api/contact/v2/departments/list?offset=1&limit=100&recursiveflag=0&deptCode="+deptCode,headsMap);
            if(object!=null&&"0".equals(object.getString("code"))){
                res = object.getJSONArray("departmentInfo");
            }
        }
        return res;
    }


    /**
     * @接口说明: 获取部门下的用户信息
     * @日期: 2020/3/13
     * @作者: 张航宁
     */
    public JSONArray getUsersByDeptId(String deptCode, String page, String pageSize){
        JSONArray res = null;
        JSONObject jsonObject = null;
        if(!StringUtils.checkNull(deptCode)){
            headsMap.put("x-wlk-Authorization",getAccessToken());
            jsonObject = HttpClientUtil.httpGetWithHeads("https://open.welink.huaweicloud.com/api/contact/v1/user/users?pageNo="+page+"&pageSize="+pageSize+"&deptCode="+deptCode,headsMap);
            if(jsonObject!=null&&"0".equals(jsonObject.getString("code"))){
                res = jsonObject.getJSONArray("data");
            }
        } else {
            deptCode = "0";
            headsMap.put("x-wlk-Authorization",getAccessToken());
            jsonObject = HttpClientUtil.httpGetWithHeads("https://open.welink.huaweicloud.com/api/contact/v1/user/users?pageNo="+page+"&pageSize="+pageSize+"&deptCode="+deptCode,headsMap);
            if(jsonObject!=null&&"0".equals(jsonObject.getString("code"))){
                res = jsonObject.getJSONArray("data");
            }
        }
        if(jsonObject!=null&&"0".equals(jsonObject.getString("code"))&&jsonObject.getInt("total")>Integer.parseInt(page)*Integer.parseInt(pageSize)){
            JSONArray usersByDeptId = getUsersByDeptId(deptCode, String.valueOf(Integer.parseInt(page) + 1), pageSize);
            if(usersByDeptId!=null&&usersByDeptId.size()>0)
                res.addAll(usersByDeptId);
        }
        return res;
    }

    /**
     * @接口说明: 获取全部部门 递归遍历
     * @日期: 2020/4/23
     * @作者: 张航宁
     */
    public JSONArray getAllDepartments(){
        JSONArray res = null;
        headsMap.put("x-wlk-Authorization",getAccessToken());
        JSONObject object = HttpClientUtil.httpGetWithHeads("https://open.welink.huaweicloud.com/api/contact/v2/departments/list?offset=1&limit=100&recursiveflag=0&deptCode=0",headsMap);
        if(object!=null&&"0".equals(object.getString("code"))){
            JSONArray departmentInfo = object.getJSONArray("departmentInfo");
            res = departmentInfo;
            getAllChildrenDept(res, departmentInfo);
        }
        return res;
    }

    private void getAllChildrenDept(JSONArray res, JSONArray departmentInfo) {
        for (int i = 0; i < departmentInfo.size(); i++) {
            JSONObject jsonObject = departmentInfo.getJSONObject(i);
            JSONArray childrenDepts = getDepartments(jsonObject.getString("deptCode"));
            if(childrenDepts!=null&&childrenDepts.size()>0){
                getAllChildrenDept(res,childrenDepts);
                res.addAll(childrenDepts);
            }
        }
    }

    /**
     * @接口说明: welink同步组织接口
     * @日期: 2020/3/18
     * @作者: 张航宁
     */
    public String WlDeptToOA(){
        JSONArray departments = getAllDepartments();
        for (int i = 0; i < departments.size(); i++) {
            JSONObject jsonObject = departments.getJSONObject(i);
            insertDept(jsonObject);
        }
        departmentService.updateDeptNo(0,"");

        return "true";
    }

    /**
     * @接口说明: welink同步用户接口
     * @日期: 2020/4/21
     * @作者: 张航宁
     */
    public String WlUserToOA(HttpServletRequest request){
        // 获取所有部门
        JSONArray departments = getDepartments("0");
        if(departments!=null){
            // 循环部门
            for (int i = 0; i < departments.size(); i++) {
                JSONObject jsonObject = departments.getJSONObject(i);
                String id = jsonObject.getString("deptCode");
                // 根据企业微信的部门id获取部门
                Department departmentWl = departmentMapper.getDeptByWlDeptId(id);
                // 如果部门为空的话 插入部门
                if(departmentWl==null){
                    insertDept(jsonObject);
                    departmentWl = departmentMapper.getDeptByWlDeptId(id);
                    if(departmentWl!=null){
                        insertUser(request, id, departmentWl);
                    }
                } else {
                    // 插入或者更新用户
                    insertUser(request, id, departmentWl);
                }
            }
        }

        return "true";
    }





    /**
     * @接口说明: 插入用户
     * @日期: 2020/3/19
     * @作者: 张航宁
     */
    private void insertUser(HttpServletRequest request, String id, Department departmentWl) {
        UserPriv minNoUserPriv = userPrivMapper.getMinNoUserPriv();
        JSONArray welinkUsers = getUsersByDeptId(id,"1","50");
        if(welinkUsers!=null){
            for (int i=0,size=welinkUsers.size();i<size;i++) {
                JSONObject userJson = welinkUsers.getJSONObject(i);
                Users users = new Users();
                String mobileNumber = userJson.getString("mobileNumber");
                users.setByname(mobileNumber.substring(mobileNumber.indexOf("-"+1)));// 登录账户名
                users.setUserName(userJson.getString("userNameCn"));
                users.setDeptId(departmentWl.getDeptId());
                users.setDeptName(departmentWl.getDeptName());
                users.setSex(userJson.getString("sex").equals("M") ? "0" : "1");
                users.setMobilNo(mobileNumber.substring(mobileNumber.indexOf("-"+1)));
                users.setEmail(userJson.getString("userEmail"));
                users.setOicqNo(userJson.getString("userId"));

                users.setUserPriv(minNoUserPriv.getUserPriv());
                users.setUserPrivName(minNoUserPriv.getPrivName());

                // 辅助部门 目前welink中没有辅助部门概念 暂时注释掉这块企业微信中复制过来的代卖
            /*String[] department = userJson.getDepartment();
            StringBuilder deptOther = new StringBuilder();
            for (String wxDeptId:department) {
                Department departmentWlOther = departmentMapper.getDeptByWxDeptId(Integer.parseInt(wxDeptId));
                if(departmentWlOther!=null){
                    deptOther.append(departmentWlOther.getDeptId()).append(",");
                }
            }
            users.setDeptIdOther(deptOther.toString());*/

                // 设置其他默认信息
                users.setPassword("");
                users.setTheme((byte) 6);
                users.setPostPriv("0");
                users.setNotLogin((byte) 0);
                // 插入用户
                Users usersBybyname = usersMapper.getUsersBybyname(users.getByname());
                if (usersBybyname == null) {
                    ToJson<Users> usersToJson = usersService.addUser(users, new UserExt(), new ModulePriv(), request);
                    if (usersToJson.isFlag()) {
                        Users users1 = (Users) usersToJson.getObject();
                        UserWeLink userWeLink = userWeLinkMapper.selectByWlUserId(userJson.getString("userId"));
                        if (userWeLink == null) {
                            userWeLink = new UserWeLink();
                            userWeLink.setOaUserId(users1.getUserId());
                            userWeLink.setWlUserId(userJson.getString("userId"));
                        }
                        userWeLinkMapper.insertSelective(userWeLink);
                    }
                }
            }
        }

    }

    /**
     * @接口说明: 递归插入部门 由低级向上级遍历
     * @日期: 2020/3/19
     * @作者: 张航宁
     */
    private void insertDept(JSONObject jsonObject) {
        String id = jsonObject.getString("deptCode");
        String name = jsonObject.getString("deptNameCn");
        String parentid = "";
        if(!StringUtils.checkNull(id)){
            try{
                parentid = jsonObject.getString("parentCode");
            }catch (Exception e){
                parentid = jsonObject.getString("fatherCode");
            }
        }
        // 查询当前部门
        Department departmentWl = departmentMapper.getDeptByWlDeptId(id);
        // 判断是否存在当前部门
        if(departmentWl==null){
            // 如果不存在 判断他是否是最外级的部门
            if(!"0".equals(id)){
                // 不是最外级别的部门 查询他的父级别部门是否存在
                Department departmentWlParent = departmentMapper.getDeptByWlDeptId(parentid);
                // 不存在进行递归向上获取
                if(departmentWlParent==null){
                    JSONObject department = getDepartment(String.valueOf(parentid));
                    if(department.getString("deptCode").equals(parentid)){
                        insertDept(department);
                    }
                } else {  // 存在执行插入操作
                    departmentWl = new Department();
                    departmentWl.setWeLinkDept(id);
                    departmentWl.setDeptName(name);
                    departmentWl.setDeptParent(departmentWlParent.getDeptId());
                    departmentMapper.insertDept(departmentWl);
                }
            } else {
                // 插入 departmentWl
                departmentWl = new Department();
                departmentWl.setWeLinkDept(id);
                departmentWl.setDeptName(name);
                departmentWl.setDeptParent(0);
                departmentMapper.insertDept(departmentWl);
            }
        } else {
            // 如果存在 查看名称是否不同 是否需要进行更新
            if(!StringUtils.checkNull(name)&&!name.equals(departmentWl.getDeptName())){
                departmentWl.setDeptName(name);
                departmentMapper.editDept(departmentWl);
            }
        }
    }

}
